<?php

namespace App\Http\Controllers\API\Tools;

use App\Http\Controllers\Controller;
use App\Miya\Models\Msg;
use App\Miya\Models\MsgForm;
use App\Miya\Tools\NoteTool;
use Ichynul\Configx\ConfigxModel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class MessageController extends Controller
{
    public function index()
    {
        //表单验证
        $form = MsgForm::with(['fields'])->find(request()->route('form'));
        if (!$form) {
            $msg = sprintf('提交失败,未找到id为 %s 的自定义表单数据!', request()->route('form'));
            return ['msg' => $msg];
        }

        //字段必填验证
        $checkResult = [];
        $form->fields->each(function ($field) use (&$checkResult) {
            $checkResult[$field->name] = !($field->is_required == 1 && empty(request()->input($field->name)));
        });
        if (in_array(false, $checkResult)) {
            $requiredFailFields = array_filter($checkResult, function ($value) {
                return !$value;
            });
            $msg = sprintf('提交失败,字段:%s 未填写!', implode(',', array_keys($requiredFailFields)));
            return ['msg' => $msg];
        }

        $msg = [
            'msg_form_id' => request()->route('form'),
            'time' => now()->format('Y-m-d H:i'),
            'ip' => request()->getClientIp()
        ];
        $data = [];
        $form->fields->each(function ($field) use (&$data) {
            $data[$field->field] = request()->input($field->name);
        });
        $msg['data'] = $data;

        try {
            Msg::create($msg);

            //短信通知网站管理员
            $key = 'note.balance';
            if (
                config('setting.phone_hint') &&
                config('setting.phone') &&
                config($key) > 0
            ) {
                if (config($key) != cache()->get($key)) return;

                NoteTool::sendMsg(
                    '216522',
                    config('setting.phone'),
                    sprintf('#web#=%s(%s)',
                        config('web.name'),
                        implode(' ', $data)
                    )
                );

                $config = ConfigxModel::whereName($key)->first();
                $config->value--;
                $config->save();

                $num = Cache::get($key);
                cache()->set($key, $num - 1);
            }

            return ['msg' => $form->response_hint];
        } catch (QueryException $exception) {
            //设置了唯一键
            return ['msg' => '提交失败,可能提交次数过于频繁,请稍后再次尝试!'];
        }
    }
}
